package thread;

import java.util.function.IntConsumer;

public class leetCode1195 {
    private int n;
    private final Object lock = new Object();
    private int i = 1;

    public leetCode1195(int n) {
        this.n = n;
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        synchronized (lock) {
            while (i <= n){
                if(i % 3 == 0 && i%5 != 0) {
                    i++;
                    printFizz.run();
                    lock.notifyAll();
                }else{
                    lock.wait();
                }

            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        synchronized (lock) {
            while (i <= n){
                if(i % 3 != 0 && i % 5 == 0) {
                    i++;
                    printBuzz.run();
                    lock.notifyAll();
                }else{
                    lock.wait();
                }

            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        synchronized (lock) {
            while (i <= n){
                if(i % 3 == 0 && i%5 == 0) {
                    i++;
                    printFizzBuzz.run();
                    lock.notifyAll();
                }else{
                    lock.wait();
                }
            }
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        synchronized (lock) {
            while (i <= n){
                if(i % 3 != 0 && i%5 != 0) {
                    printNumber.accept(i);
                    i++;
                    lock.notifyAll();
                }else{
                    lock.wait();
                }
            }
        }
    }

}
